package practice_list;

/**
 * Created with Intellij JDEA
 * Description:
 * User:
 * Date:2022-03-28
 * Time:9:48
 */
public class 反转链表II {
    private void reverseLinkedList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
    }
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(head.next == null || left - right == 0) {
            return head;
        }
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;

        ListNode cur = dummyNode;
        ListNode rightNood = dummyNode;
        while(left > 1){
            cur = cur.next;
            left--;
        }

        ListNode leftNode = cur.next;
        while(right > 0){
            rightNood = rightNood.next;
            right--;
        }
        ListNode end = rightNood.next;

        cur.next = null;
        rightNood.next = null;

        reverseLinkedList(leftNode);

        cur.next = rightNood;
        leftNode.next = end;

        return dummyNode.next;
    }
}

